package com.ywwxhz.app;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ListFragment;
import android.util.SparseIntArray;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.ywwxhz.PkgMgr.R;
import com.ywwxhz.adapter.AppInfoAdapter;
import com.ywwxhz.lib.BackupAsyncTask;
import com.ywwxhz.model.AppInfo;
import com.ywwxhz.model.Category;
import com.ywwxhz.util.Util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ApplicationFragment extends ListFragment {
    OnItemClickListener listener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            select(view, position);
        }
    };
    AdapterView.OnItemLongClickListener longClickListener = new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            select(view, i);
            return true;
        }
    };
    private Category category;
    private AppInfoAdapter adapter;
    private SparseIntArray map = new SparseIntArray();
    private ActionMode actionMode;
    private boolean inmode = false;
    private LinearLayout fackFooter;
    private AbsListView.LayoutParams footerParams;


    private void select(View view, int position) {
        AppInfo appInfo = category.getAppInfo(position);
        boolean select = !appInfo.isSelect();
        ((CheckBox) view.findViewById(R.id.select)).setChecked(select);
        appInfo.setSelect(select);
        if (select) {
            map.put(position, position);
        } else {
            map.delete(position);
        }
        view.setActivated(select);
        if (!inmode) {
            actionMode = getActivity().startActionMode(new ChoiseMode());
        } else {
            actionMode.invalidate();
        }
    }

    public ApplicationFragment setCategory(Category category) {
        this.category = category;
        return this;
    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getListView().setFastScrollEnabled(true);
        int padding = Util.dip2px(getActivity(), 5);
        getListView().setClipToPadding(false);
        getListView().setOnItemClickListener(listener);
        getListView().setOnItemLongClickListener(longClickListener);
        getListView().setDivider(null);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            SystemBarTintManager tintManager = ((MainActivity) getActivity()).getSystemBarTintManager();
            fackFooter = new LinearLayout(getActivity());
            footerParams = new AbsListView.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, tintManager.getConfig().getPixelInsetBottom());
            fackFooter.setLayoutParams(footerParams);
            getListView().addFooterView(fackFooter, null, false);
            getListView().setPadding(padding, tintManager.getConfig().getPixelInsetTop(true), padding, 0);
        } else {
            getListView().setPadding(padding, 0, padding, 0);
        }
    }

    public void notifyDataSetChange() {
        if (getListAdapter() == null) {
            adapter = new AppInfoAdapter(getActivity(), category);
            setListAdapter(adapter);
            setListShown(true);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isVisibleToUser && inmode) {
            actionMode.finish();
            inmode = false;
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            SystemBarTintManager tintManager = ((MainActivity) getActivity()).getSystemBarTintManager();
            tintManager.getConfig().onConfigurationChanged(newConfig);
            footerParams.height = tintManager.getConfig().getPixelInsetBottom();
        }
    }

    class ChoiseMode implements ActionMode.Callback {

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            inmode = true;
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            menu.clear();
            switch (map.size()) {
                case 0:
                    mode.finish();
                    break;
                case 1:
                    AppInfo appInfo = category.getAppInfo(map.valueAt(0));
                    mode.setTitle(appInfo.getLabel());
                    mode.setSubtitle(appInfo.getPkgName());
                    mode.getMenuInflater().inflate(R.menu.package_selectone, menu);
                    break;
                default:
                    mode.setTitle(String.format("已选中 %d 项", map.size()));
                    mode.setSubtitle(null);
                    mode.getMenuInflater().inflate(R.menu.package_selectmore, menu);
                    if (map.size() == category.getSize()) {
                        menu.findItem(R.id.menu_all).setTitle(R.string.menu_selectnav);
                    }
                    break;
            }
            return true;
        }

        @SuppressWarnings("unchecked")
        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
                case R.id.menu_backup_select:
                    List<AppInfo> appInfos = new ArrayList<AppInfo>();
                    for (int i = 0; i < map.size(); i++) {
                        appInfos.add(category.getAppInfo(map.valueAt(i)));
                    }
                    ProgressDialog dialog = new ProgressDialog(getActivity());
                    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    dialog.setMax(appInfos.size());
                    dialog.setCancelable(false);
                    dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            adapter.notifyDataSetChanged();
                        }
                    });
                    dialog.setMessage("备份中请稍候");
                    try {
                        new BackupAsyncTask(getActivity(), dialog)
                                .execute(appInfos);
                    } catch (Exception e) {
                        dialog.dismiss();
                        Toast.makeText(
                                getActivity(),
                                "something error has occurred: "
                                        + e.getLocalizedMessage(),
                                Toast.LENGTH_LONG
                        ).show();
                        e.printStackTrace();
                    }
                    mode.finish();
                    break;

                case R.id.menu_all:
                    if (map.size() < category.getSize()) {
                        for (int i = 0; i < category.getSize(); i++) {
                            category.getAppInfo(i).setSelect(true);
                            map.put(i, i);
                        }
                        adapter.notifyDataSetChanged();
                        mode.invalidate();
                    } else {
                        mode.finish();
                    }
                    break;
                case R.id.menu_share:
                    File sourceFile = new File(category.getAppInfo(map.valueAt(0))
                            .getSourceDir());
                    // 调用android系统的分享窗口
                    Intent shareintent = new Intent();
                    shareintent.setAction(Intent.ACTION_SEND);
                    shareintent.setType("application/zip");
                    shareintent.putExtra(Intent.EXTRA_STREAM,
                            Uri.fromFile(sourceFile));
                    startActivity(shareintent);
                    mode.finish();
                    break;
                case R.id.menu_delete:
                    Uri packageURI = Uri.parse("package:"
                            + category.getAppInfo(map.valueAt(0)).getPkgName());
                    Intent uninstallIntent = new Intent(Intent.ACTION_DELETE,
                            packageURI);
                    uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(uninstallIntent);
                    adapter.notifyDataSetChanged();
                    mode.finish();
                    break;
                case R.id.menu_detail:
                    Intent detailintent = new Intent(
                            Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package",
                            category.getAppInfo(map.valueAt(0)).getPkgName(), null);
                    detailintent.setData(uri);
                    startActivity(detailintent);
                    mode.finish();
                    break;
                default:
                    break;
            }
            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            for (AppInfo appInfo : category.getApps()) {
                appInfo.setSelect(false);
            }
            map.clear();
            adapter.notifyDataSetChanged();
            inmode = false;
        }

    }
}
